import axios from 'axios'

axios.defaults.baseURL = 'http://localhost:8080/'
axios.defaults.withCredentials = true

/**
const myAxios = axios.create({
  baseURL: 'http://localhost:8080/',
  timeout: 10000,
  withCredentials: true,
  transformRequest: [(data) => JSON.stringify(data.data)],
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json'
  }
})
*/

// POST传参序列化(添加请求拦截器)
axios.interceptors.request.use(config => {
  // 在发送请求之前做某件事
  /**
  if (config.method === 'post') {
    // JSON 转换为 FormData
    const formData = new FormData()
    Object.keys(config.data).forEach(key => formData.append(key, config.data[key]))
    config.data = formData
  }
  */

  // 下面会说在什么时候存储 token
  if (localStorage.token) {
    config.headers.Authorization = 'Bearer ' + localStorage.token
  }
  return config
}, error => {
  alert('错误的传参', 'fail')
  return Promise.reject(error)
})

// 返回状态判断(添加响应拦截器)
axios.interceptors.response.use(resp => { return resp }, error => {
  if (error.response.status === 401) {
    // 401 说明 token 验证失败
    location.href = '/#/component/sign-in'
  } else {
     // 超时重新请求token
  }
  // 返回 response 里的错误信息
  return Promise.reject(error.response.data)
})

// 使用axios作为http请求
export default {
  install (Vue) {
    Vue.prototype.$http = axios
    Vue.http = axios
  },
  $http: axios
}

export const $http = axios
